import React, { forwardRef, useEffect, useState, useImperativeHandle } from 'react'
import TextField from '@mui/material/TextField'
import Button from '@mui/material/Button'
import { addApiDoc } from '@/api/apidoc'

export interface ApiDocFormHandle{
  clear:()=>void
  submit:()=>void
}

interface Props{
  name?:string
  router?:string
  link?:string
  desc?:string
  onSuccess?:()=>void
}

function ApiDocForm (props:Props, ref:any) {
  const [ name, setName ] = useState('')
  const [ router, setRouter ] = useState('')
  const [ link, setLink ] = useState('')
  const [ desc, setDesc ] = useState('')
  const [ error, setError ] = useState('')

  useEffect(() => {
    setName(props.name ?? '')
    setRouter(props.router ?? '')
    setLink(props.link ?? '')
    setDesc(props.desc ?? '')
  }, [ props ])

  useImperativeHandle(ref, ():ApiDocFormHandle => ({
    clear: clear,
    submit: submit,
  }))

  const clear = () => {
    setName('')
    setRouter('')
    setLink('')
    setDesc('')
  }

  const submit = async () => {
    try {
      const res = await addApiDoc({
        name: name,
        router: router,
        link: link,
        desc: desc,
      })
      if (res?.id > 0) {
        clear()
        props?.onSuccess?.()
      } else {
        setError(res)
      }
    } catch (err) {
      console.log(err)
    }
  }

  return <React.Fragment>
    <div style={{ width: '100%', boxSizing: 'border-box', padding: 24, display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
      <TextField style={{ width: '100%', marginBottom: 20 }} variant='outlined' label="文档名称" onChange={(e) => setName(e.target.value)}  value={name}/>
      <TextField style={{ width: '100%', marginBottom: 20  }} variant='outlined' label="路由名称" onChange={(e) => setRouter(e.target.value)}  value={router}/>
      <TextField
        style={{ width: '100%', marginBottom: 20  }}
        variant='outlined'
        multiline
        maxRows={4}
        label="文档链接"
        onChange={(e) => setLink(e.target.value)}
        value={link}/>
      <TextField
        style={{ width: '100%', marginBottom: 20  }}
        variant='outlined'
        label="描述"
        multiline
        maxRows={4}
        onChange={(e) => setDesc(e.target.value)}
        value={desc}/>
      <div style={{ display: 'flex' }}>
        <Button variant="contained" onClick={submit}>提交</Button>
        <div style={{ color: 'red' }}>{error}</div>
      </div>
    </div>
  </React.Fragment>
}

export default forwardRef(ApiDocForm)
